package com.mht2017.common.utils;

import com.mht2017.common.db.DataSource;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author yutong.xiao
 */
public class DBUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(DBUtil.class);

	public static String getUrl(DataSource dataSource) {
		if (StringUtils.equals("oracle", dataSource.getType())) {
			return "jdbc:oracle:thin:@" + dataSource.getIp() + ":" + dataSource.getPort() + ":" + dataSource.getSid();
		} else {
			return String.format("jdbc:mysql://%s:%s/%s?zeroDateTimeBehavior=convertToNull", dataSource.getIp(), dataSource.getPort(), dataSource.getSid());
		}
	}

	public static String getDriverName(String dataSourceType) {
		return StringUtils.equals("oracle", dataSourceType) ? "oracle.jdbc.driver.OracleDriver" : "com.mysql.jdbc.Driver";
	}

	public static void close(AutoCloseable... closeables) {
		if (null == closeables) {
			return;
		}

		for (AutoCloseable closeable : closeables) {
			if (null != closeable) {
				try {
					closeable.close();
				} catch (Exception e) {
					LOGGER.error(String.format("关闭出错: '%s'", closeable), e);
				}
			}
		}
	}

}
